﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Easy.BLL;

namespace Easy.Web.Service.Data
{
    /// <summary>
    /// Js控制文件
    /// </summary>
    public class JsHub : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string itemtype = context.Request["itemtype"];
            string EntityName = context.Request["entityname"];
            string ItemName = context.Request["itemname"];
            if (String.IsNullOrWhiteSpace(ItemName))
            {
                ItemName = "DefaultView";
            }
            string nonmatch = context.Request.Headers["If-None-Match"];
            List<String> JsNameArray;
            try
            {
                JsNameArray = JsonConvert.DeserializeObject<List<String>>(context.Request["jsnamearray"]);
            }
            catch (Exception)
            {
                JsNameArray = null;
            }
            context.Response.ContentType = context.Request.RequestType.ToLower() == "get".ToLower()
                ? "application/javascript"
                : "text/plain";
            JsHubBLL bll = new JsHubBLL();
            if (context.Request.RequestType.ToLower() == "get")
            {
                if (String.IsNullOrWhiteSpace(itemtype) || String.IsNullOrWhiteSpace(EntityName))
                {
                    if (JsNameArray != null)
                    {
                        var ret = bll.GetJsWithNameArray(JsNameArray.Cast<object>().ToList());
                        string etag = MD5Encrypt(ret);
                        if (etag == nonmatch)
                        {
                            context.Response.StatusCode = 304;
                            return;
                        }
                        context.Response.AddHeader("etag", etag);
                        context.Response.Write(ret);
                    }
                    else
                    {
                        context.Response.StatusCode=404;
                    }
                }
                else
                {
                    string jsContent = bll.GetJsWithEntityItemName(itemtype, EntityName, ItemName);
                    string etag = MD5Encrypt(jsContent);
                    if (etag == nonmatch)
                    {
                        context.Response.StatusCode = 304;
                        return;
                    }
                    context.Response.AddHeader("etag",etag);
                    context.Response.Write(jsContent);
                }
                
            }
            else
            {
                if (context.Request["action"].Trim().ToLower() == "compress")
                {
                    JObject obj = new JObject();
                    obj["Type"] = "Compress";
                    obj["data"] = bll.GetCompressContent(context.Request["jscontent"]);
                    context.Response.Write(JsonConvert.SerializeObject(obj));
                    return;
                }

                if (context.Request["action"].Trim().ToLower() == "getjslist")
                {
                    context.Response.Write(JsonConvert.SerializeObject(bll.GetAllJsList(null,null)));
                    return;
                }
                else
                {
                    context.Response.Write(bll.GetJsWithEntityItemName(itemtype, EntityName, ItemName));
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <returns></returns>
        public static string MD5Encrypt(string input)
        {
            return MD5Encrypt(input, new UTF8Encoding());
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <param name="encode">字符的编码</param>
        /// <returns></returns>
        public static string MD5Encrypt(string input, Encoding encode)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(encode.GetBytes(input));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            return sb.ToString();
        }
    }
}